package router

import (
	"gddgame.cc/galaxy/asteroid"
	"gddgame.cc/galaxy/asteroid/cluster"
	"gddgame.cc/galaxy/binocle"
	. "gddgame.cc/galaxy/common/dsl/db"
	. "gddgame.cc/galaxy/common/dsl/web"
	"gddgame.cc/galaxy/core/routers"
	"gddgame.cc/galaxy/project/star/star/controller"

	"gddgame.cc/galaxy/server/composer"
	"gddgame.cc/galaxy/server/web"
)

func SystemHandler(path string, builder composer.Builder, router web.Router) {
	var agent binocle.App
	builder.Factory("agent", &agent)

	agent.AddMasterListen(func(node cluster.Node) {
		client := agent.Client()
		if err := controller.RunZone(builder, client); err != nil {
			builder.Error(err)
		}
	})
	agent.MountNode(func(node cluster.Node) {
		// 战区事件转发
		node.On(controller.WarEvent, controller.BindZoneEvent)
	})
	agent.UnMountClient(func(client *cluster.Client) {
		if agent.IsMaster() {
			if err := controller.CloseZone(builder); err != nil {
				builder.Error(err)
			}
		}
	})
	agent.MountClient(func(client *cluster.Client) {
		client.On("reload/zone", func(message asteroid.Message) {
			if err := controller.LoadZone(builder); err != nil {
				builder.Error(err)
			}
		})
	})

	// 绑定计划任务
	agent.Schedule("UpdateAllGrade", func(args []string) error {
		return controller.UpdateAllGrade(builder)
	})
	agent.Schedule("UpdateUserAttr", func(args []string) error {
		return controller.UpdateUserAttr(builder)
	})

	r := NewSwaggerRouter(path, builder, router, &SwaggerRouterConfig{
		Info: SwaggerInfo{
			Title: "",
		},
	})

	web.Restful(router)
	routers.ManageRouterBind(builder, r)
	controller.Env.BindRouter(r)

	_ = TableRouterWith(builder, r.Group("/db"), agent.Name())
}
